package com.typing.battle.service;

import java.net.SocketTimeoutException;
import java.util.HashMap;
import java.util.Timer;
import java.util.TimerTask;

import org.json.JSONArray;
import org.json.JSONObject;


import com.typing.battle.listener.OnDataSyncCompleteListener;
import com.typing.battle.receiver.C2dmBroadcastReceiver;
import com.typing.battle.util.PreferenceMgr;
import com.typing.battle.util.ServerComunicationUtil;
import com.typing.battle.value.ServerComunicationDTO;


import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;

public class TypingBattlePollingService extends Service implements OnDataSyncCompleteListener{
	
	private String email , roomId;
	private Context mContext;
	private Thread syncThread;
	private boolean syncThreadIsAlive = false;
	
	private ITypingBattlePollingService.Stub serviceStub = new ITypingBattlePollingService.Stub() {    	
		@Override
		public void startChatMessageSync(String email,String roomId) throws RemoteException {
			// TODO Auto-generated method stub
			setInfo(email,roomId);
			syncThreadIsAlive = true;
			messageSync();
		}
		@Override
		public void stopChatMessageSync() throws RemoteException {
			// TODO Auto-generated method stub
			stopMessageSync();
		}
    };    
    private void setInfo(String email,String roomId){
    	this.email = email;
    	this.roomId = roomId;
    }
    private void stopMessageSync(){
    	syncThreadIsAlive = false;
    	//if(syncThread != null)
    		//syncThread.stop();
    }
    private void messageSync(){
    	/*ServerComunicationDTO dto = new ServerComunicationDTO();
		dto.setActionType(ServerComunicationUtil.TYPE_SERVER_SYNC_START);
		dto.setResponseType(ServerComunicationUtil.RETURN_TYPE_STRING);
		dto.setTimeoutInterval(5*60*1000);
		dto.setUserEmail(email);
		String result = "";
		try {
			result = (String)ServerComunicationUtil.serverAction(dto, mContext);
		} catch (Exception e) {
			e.printStackTrace();
		}*/
    	/*Runnable run = new Runnable(){

			@Override
			public void run() {
				// TODO Auto-generated method stub
				while(syncThreadIsAlive){
					ServerComunicationDTO dto = new ServerComunicationDTO();
					dto.setActionType(ServerComunicationUtil.TYPE_SERVER_SYNC);
					dto.setResponseType(ServerComunicationUtil.RETURN_TYPE_STRING);
					dto.setTimeoutInterval((int)(1.5*60*1000));
					dto.setReceiveEmail(email);
					dto.setChatRoomId(roomId);
					String result = "";
					try {
						ServerComunicationUtil.serverAction(dto, mContext,service);
					} catch (SocketTimeoutException e) {
						Log.d("serveice","timeout");
						
					} catch (Exception e) {
						e.printStackTrace();
						break;
					}
				}
			}
    		
    	};
				
		syncThread = new Thread(run);
		syncThread.start();*/
    	AsyncTask<String, Void, Object> task = new AsyncTask<String, Void, Object>() {

			@Override
			protected Object doInBackground(String... params) {
				// TODO Auto-generated method stub
				while(syncThreadIsAlive){
					ServerComunicationDTO dto = new ServerComunicationDTO();
					dto.setActionType(ServerComunicationUtil.TYPE_SERVER_SYNC);
					dto.setResponseType(ServerComunicationUtil.RETURN_TYPE_STRING);
					dto.setTimeoutInterval((int)(1.5*60*1000));
					dto.setReceiveEmail(email);
					dto.setChatRoomId(roomId);
					String result = "";
					try {
						result = (String)ServerComunicationUtil.pollingAction(dto, mContext);
					} catch (SocketTimeoutException e) {
						Log.d("serveice","timeout");
						
					} catch (Exception e) {
						e.printStackTrace();
						break;
					}
					if(result==null)
						onSyncComplete(OnDataSyncCompleteListener.RESULT_SYNC_FAIL,dto , "retry");
					else
						onSyncComplete(OnDataSyncCompleteListener.RESULT_SYNC_SUCCESS,dto , result);
				}
				return null;
			}
			
    		
    	};
    	task.execute();
    	
    }
    public void sendBroadcast(String str){
    	
    	JSONArray array = null;
    	try{
    		array = new JSONArray(str);
    	Log.d("", "sendBroadcast====>>"+array.toString());
	    	for(int i=0 ; i < array.length(); i++){
	    		JSONObject data = new JSONObject(array.get(i).toString());
	    		Intent intent = new Intent("com.typing.battle.polling.RECEIVE"); 
	    		Log.d("sendBroadcast",data.get("userEmail").toString());
	    		intent.putExtra("msg_from_name", data.get("senderName").toString());
	    		intent.putExtra("msg_from", data.get("userEmail").toString());
	    		intent.putExtra("msg", data.get("msg").toString());
	    		intent.putExtra("sendType", data.get("sendType").toString());
	    		if("6".equals(data.get("sendType").toString())){
	    			String msg = data.get("msg").toString();
	    			Log.d("msgString",msg);
	    			Log.d("indexOf",msg.indexOf("sentence=")+ " | " + msg.indexOf("/",msg.indexOf("sentence=")));
	    			intent.putExtra("sentence", msg.substring(msg.indexOf("sentence=") + 9, msg.indexOf("/",msg.indexOf("sentence="))));
	    			Log.d("indexOf",msg.indexOf("sentenceId=")+ " | " + msg.indexOf("/",msg.indexOf("sentenceId=")));
	    			intent.putExtra("sentenceId", msg.substring(msg.indexOf("sentenceId=") + 11, msg.indexOf("/",msg.indexOf("sentenceId="))));
	    			Log.d("indexOf",msg.indexOf("seq=")+ " | " + msg.indexOf("/",msg.indexOf("seq=")));
	    			intent.putExtra("seq", msg.substring(msg.indexOf("seq=") + 4, msg.indexOf("/",msg.indexOf("seq="))));
	    			
	    		}
	        	mContext.sendBroadcast(intent);   
	    	}
    	}catch(Exception e){
    		e.printStackTrace();
    	}
    }
    @Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
    	
		return serviceStub;
	}
	@Override
	public void onRebind(Intent intent) {
		// TODO Auto-generated method stub
		super.onRebind(intent);
	}	
	@Override
	public boolean onUnbind(Intent intent) {
		// TODO Auto-generated method stub
		super.onUnbind(intent);
		stopMessageSync();
		
		ServerComunicationDTO dto = new ServerComunicationDTO();
		dto.setActionType(ServerComunicationUtil.TYPE_SERVER_SYNC_END);
		dto.setResponseType(ServerComunicationUtil.RETURN_TYPE_STRING);
		dto.setTimeoutInterval(5*60*1000);
		dto.setUserEmail(email);
		String result = "";
		try {
			ServerComunicationUtil.serverAction(dto, mContext,TypingBattlePollingService.this);
		} catch (Exception e) {
			e.printStackTrace();
		}
		Log.d("service unbind","unbind");
		return true;
	}	
	@Override    
	public void onStart(Intent intent, int startId) {
		
		super.onStart(intent, startId);         
		
	}       
	@Override    
	public void onDestroy() {    
		Log.d("service destroy","destroy");
		super.onDestroy();    
		
	}	
	@Override
	public void onCreate() {
		// TODO Auto-generated method stub
		super.onCreate();
		mContext = this;
		
	}
	@Override
	public void onSyncComplete(int resultCode) {
		// TODO Auto-generated method stub
		
	}
	@Override
	public void onSyncComplete(int resultCode, ServerComunicationDTO dto, Object resultObj) {
		if(resultCode == OnDataSyncCompleteListener.RESULT_SYNC_FAIL){
			if(resultObj!=null)
				ServerComunicationUtil.showNotify((String)resultObj, this);
		}else{
			//if(dto.getActionType() == ServerComunicationUtil.TYPE_SERVER_SYNC_END){
				String result = "";
				try {
					result = (String)resultObj;
				} catch (Exception e) {
					e.printStackTrace();
				}
				if(!"".equals(result) && result.length() >5 && !"FAIL".equals(result.trim())){
					sendBroadcast(result);
				}
			//}		
		}
//		super.onSyncComplete(resultCode, actionType, resultObj);
	}

}
